//
//  CZEmotionManager.swift
//  刷新控件
//
//  Created by Albert Zhu on 16/10/25.
//  Copyright © 2016年 Albert Zhu. All rights reserved.
//

import UIKit

class CZEmotionManager {
    /// 表情管理器单例
    static let shared = CZEmotionManager()
    
    /// 用于存放表情包的集合
    lazy var packages = [CZEmotionPackage]()
    
    var bundle: Bundle? {
        guard let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil) else {return nil}
        
        return Bundle(path: path)
    }
    
    /// 私有化构造函数，保证单例调用的唯一性
    ///
    /// - returns:
    private init() {
        loadPackages()
    }
    
    func recentEmotion(em: CZEmotionModel) {
        em.times += 1
        
        if !packages[0].emotions.contains(em) {
            packages[0].emotions.append(em)
        }
        
        packages[0].emotions.sort { (em1, em2) -> Bool in
            return em1.times > em2.times
        }
        
        if packages[0].emotions.count > 20 {
            packages[0].emotions.removeSubrange(20..<packages[0].emotions.count)
        }
    }
}

// MARK: - 表情包数据
extension CZEmotionManager {
    
    /// 从bundle中提取表情包
    func loadPackages() {
        guard let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil),
        let bundle = Bundle(path: path),
        let plistPath = bundle.path(forResource: "emoticons.plist", ofType: nil),
        let dic = NSDictionary.init(contentsOfFile: plistPath) as? [String:Any],
        let array = dic["packages"] as? [[String:Any]],
        let models = NSArray.yy_modelArray(with: CZEmotionPackage.self, json: array) as? [CZEmotionPackage]
        else {return}
        
        packages += models
    }
}

// MARK: - 表情符号处理
extension CZEmotionManager {
    /// 根据服务器返回的纯文本在所有表情符号中查找对应的表情模型对象
    ///
    /// - 如果找到，返回表情模型
    /// - 否则返回nil
    func findEmotion(string: String) -> CZEmotionModel? {
        // 遍历表情包集合数组
        for package in packages {
            // 在各个表情包中查找表情模型对应的纯文本是否和参数的纯文本相同
            let result = package.emotions.filter() {$0.chs == string}
            
            if result.count == 1 {
                return result[0]
            }
        }
        
        return nil
    }
    
    /// 通过给定的字符串转换成图文混排的属性文本
    ///
    /// - parameter string: 给定的字符串
    ///
    /// - returns: 图文混排的属性文本
    func emotionString(string: String, font: UIFont) -> NSAttributedString {
        let attr = NSMutableAttributedString(string: string)
        
        // 正则找出所有带有[xxx]的子字符串
        let pattern = "\\[.*?\\]"
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else {return attr}
        
        let matches = regx.matches(in: string, options: [], range: NSRange(location: 0, length: attr.length))
        
        // 倒序遍历替换，不会影响格式(字符串长度改变，正序遍历会出错)
        for m in matches.reversed() {
            // 找到所有符合正则的子串
            let r = m.rangeAt(0)
            let subStr = (attr.string as NSString).substring(with: r)
            
            // 表情包通过子串查找符合的表情模型，并返回
            if let model = CZEmotionManager.shared.findEmotion(string: subStr) {
                // 通过表情模型和对应的range逐个替换为图片
                attr.replaceCharacters(in: r, with: model.imageText(font: font))
            }
        }
        
        return attr
    }
}
